package com.example.interceptor;

import java.sql.Connection;

import javax.servlet.ServletContext;
import javax.sql.DataSource;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import net.vsame.url2sql.helper.Url2SqlContext;
import net.vsame.url2sql.url.Interceptor;
import net.vsame.url2sql.url.impl.UrlMapping;
import net.vsame.url2sql.url.impl.UrlMapping.Chain;

public class BaseInterceptor implements Interceptor {

	private WebApplicationContext springContext;

	@Override
	public void init(UrlMapping urlMapping, ServletContext servletContext) {
		System.out.println("==========================init==================");
		System.out.println("如果使用的是 Oracle 数据库，请打开 BaseInterceptor 15行注释");
		// SqlHelper.setJdbcUtils(new OracleJdbcUtils());

		// Mysql
		springContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		final DataSource dataSource = springContext.getBean("dataSource", DataSource.class);
		
		Url2SqlContext.setConnSource(new Url2SqlContext.ConnSource() {

			@Override
			public Connection getConnection() {
				try {
					return dataSource.getConnection();
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});
	}

	@Override
	public void invoke(Chain chain) {
		System.out
				.println("-----------------------invoke start------------------");
		long begin = System.currentTimeMillis();
		try {
			chain.next();
		} finally {
			System.out.println((System.currentTimeMillis() - begin) + "ms");
			System.out
					.println("-----------------------invoke end------------------");
		}
	}

	@Override
	public void destroy() {

	}

}
